import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Button, Table, Space, Tag, Modal, message, Form, Input, Select, InputNumber, Radio } from 'antd';
import { PlusOutlined, SyncOutlined } from '@ant-design/icons';
import ProForm, { ProFormDigit, ProFormSelect, ProFormText } from '@ant-design/pro-form';
import { queryMeituanConfigs, addMeituanConfig, updateMeituanConfig, deleteMeituanConfig, syncMeituan } from './service';
import { request } from 'umi';

const { Option } = Select;

const MeituanConfigPage = () => {
  // 状态定义
  const [configs, setConfigs] = useState([]);
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [editingRecord, setEditingRecord] = useState(null);
  const [stores, setStores] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [form] = Form.useForm();

  // 初始加载
  useEffect(() => {
    fetchStores();
    fetchConfigs();
  }, []);

  // 获取门店列表
  const fetchStores = async () => {
    try {
      const response = await request('/api/v1/store', {
        method: 'GET',
        params: { pageSize: 100, status: 1 }, // 只获取启用的门店
      });
      setStores(response.data?.list || []);
    } catch (error) {
      console.error('获取门店列表失败:', error);
    }
  };

  // 获取美团配置列表
  const fetchConfigs = async (params = {}) => {
    setLoading(true);
    try {
      const { current, pageSize, ...filters } = params;
      const response = await queryMeituanConfigs({
        page: current || pagination.current,
        page_size: pageSize || pagination.pageSize,
        ...filters,
      });
      
      setConfigs(response.data.list || []);
      setPagination({
        ...pagination,
        current: params.current || pagination.current,
        pageSize: params.pageSize || pagination.pageSize,
        total: response.data.total || 0,
      });
    } catch (error) {
      console.error('获取美团配置列表失败:', error);
      message.error('获取美团配置列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 表格分页变化
  const handleTableChange = (pagination, filters, sorter) => {
    fetchConfigs({
      current: pagination.current,
      pageSize: pagination.pageSize,
      ...filters,
    });
  };

  // 显示添加/编辑弹窗
  const showModal = (record = null) => {
    setEditingRecord(record);
    setVisible(true);
    
    // 重置表单
    form.resetFields();
    
    // 如果是编辑，填充表单
    if (record) {
      form.setFieldsValue({
        storeId: record.store_id,
        appKey: record.app_key,
        appSecret: record.app_secret,
        poiId: record.poi_id,
        syncInterval: record.sync_interval,
        status: record.status,
      });
    } else {
      // 默认值
      form.setFieldsValue({
        syncInterval: 30,
        status: 1,
      });
    }
  };

  // 关闭弹窗
  const handleCancel = () => {
    setVisible(false);
    setEditingRecord(null);
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      const formData = {
        store_id: values.storeId,
        app_key: values.appKey,
        app_secret: values.appSecret,
        poi_id: values.poiId,
        sync_interval: values.syncInterval,
        status: values.status,
      };
      
      if (editingRecord) {
        // 更新
        await updateMeituanConfig(editingRecord.id, formData);
        message.success('更新成功');
      } else {
        // 新增
        await addMeituanConfig(formData);
        message.success('添加成功');
      }
      
      setVisible(false);
      fetchConfigs();
    } catch (error) {
      console.error('保存美团配置失败:', error);
      message.error('保存失败，请检查表单');
    }
  };

  // 删除配置
  const handleDelete = async (id) => {
    try {
      await deleteMeituanConfig(id);
      message.success('删除成功');
      fetchConfigs();
    } catch (error) {
      console.error('删除美团配置失败:', error);
      message.error('删除失败');
    }
  };

  // 同步测试
  const handleSync = async (id) => {
    try {
      await syncMeituan(id);
      message.success('同步测试成功');
      fetchConfigs();
    } catch (error) {
      console.error('同步测试失败:', error);
      message.error('同步测试失败');
    }
  };

  // 确认删除
  const confirmDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除门店"${record.store_name}"的美团配置吗？`,
      onOk: () => handleDelete(record.id),
    });
  };

  // 表格列定义
  const columns = [
    {
      title: '门店名称',
      dataIndex: 'store_name',
      key: 'store_name',
    },
    {
      title: 'AppKey',
      dataIndex: 'app_key',
      key: 'app_key',
      ellipsis: true,
    },
    {
      title: '美团门店ID',
      dataIndex: 'poi_id',
      key: 'poi_id',
    },
    {
      title: '同步间隔(分钟)',
      dataIndex: 'sync_interval',
      key: 'sync_interval',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '最后同步时间',
      dataIndex: 'last_sync_time',
      key: 'last_sync_time',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => showModal(record)}>编辑</a>
          <a onClick={() => handleSync(record.id)}>同步测试</a>
          <a onClick={() => confirmDelete(record)}>删除</a>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Button type="primary" onClick={() => showModal()} icon={<PlusOutlined />}>
            添加配置
          </Button>
        </div>
        <Table
          columns={columns}
          dataSource={configs}
          rowKey="id"
          pagination={pagination}
          loading={loading}
          onChange={handleTableChange}
        />
      </Card>

      {/* 添加/编辑表单 */}
      <Modal
        title={editingRecord ? '编辑美团配置' : '添加美团配置'}
        visible={visible}
        onOk={handleSubmit}
        onCancel={handleCancel}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="storeId"
            label="所属门店"
            rules={[{ required: true, message: '请选择门店' }]}
          >
            <Select
              placeholder="请选择门店"
              disabled={editingRecord}
            >
              {stores.map(store => (
                <Option key={store.id} value={store.id}>{store.name || store.store_name}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="appKey"
            label="AppKey"
            rules={[{ required: true, message: '请输入AppKey' }]}
          >
            <Input placeholder="请输入美团开放平台AppKey" />
          </Form.Item>
          <Form.Item
            name="appSecret"
            label="AppSecret"
            rules={[{ required: true, message: '请输入AppSecret' }]}
          >
            <Input placeholder="请输入美团开放平台AppSecret" />
          </Form.Item>
          <Form.Item
            name="poiId"
            label="美团门店ID"
            rules={[{ required: true, message: '请输入美团门店ID' }]}
          >
            <Input placeholder="请输入美团门店ID(POI ID)" />
          </Form.Item>
          <Form.Item
            name="syncInterval"
            label="同步间隔(分钟)"
            rules={[{ required: true, message: '请输入同步间隔' }]}
          >
            <InputNumber
              min={5}
              max={1440}
              style={{ width: '100%' }}
              placeholder="请输入同步间隔，默认30分钟"
            />
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
          >
            <Radio.Group>
              <Radio value={1}>启用</Radio>
              <Radio value={0}>禁用</Radio>
            </Radio.Group>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default MeituanConfigPage; 